package com.yirui.serialcomm.core;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * 流连接器
 *
 * @author Dujie
 * @create 2025/8/6
 * @since 1.0.0
 */
public class Connector {
    private PipedInputStream pis = new PipedInputStream();
    private PipedOutputStream pos = new PipedOutputStream();



    public void connectTo(Connector connector) throws IOException {
        connector.getPipedOutputStream().connect(pis);
     }



    public final PipedInputStream getPipedInputStream() {
        return pis;
    }

    public final PipedOutputStream getPipedOutputStream() {
        return pos;
    }

    public final void close(){
        if(pis != null){
            try {
                pis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            pis = null;
        }

        if(pos != null){
            try {
                pos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            pos = null;
        }
    }

    public void write(byte[] buffer, int offset, int len) throws IOException {
        pos.write(buffer, offset, len); // 串口数据 → 管道
        pos.flush();

    }
    public int read(byte[] buffer) throws IOException {
        return pis.read(buffer); // 管道数据 → 处理;
    }


    public void write(byte[] buffer) throws IOException {
        write(buffer, 0, buffer.length);
    }
}
